<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch">

      <!--ADE Knowledge Base Name-->
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" placeholder="Pls input ade kb name" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!--Collection Name-->
      <el-form-item prop="collectionName">
        <el-input v-model="queryParams.collectionName" placeholder="Pls input collection name" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- Status -->
      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="Select Status" clearable>
          <el-option v-for="dict in dict.type.lab_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <!--Embed Models-->
      <el-form-item prop="embedModel">
        <el-select v-model="queryParams.embedModel" placeholder="Select Embed Model" clearable>
          <el-option v-for="dict in dict.type.embed_models" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">Search</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ade:adebase:add']">New</el-button>
      </el-col>

       <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-document" size="mini" @click="gotoRecord"
          v-hasPermi="['ade:adebase:add']">ADE KB Records</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="adebaseList" @selection-change="handleSelectionChange">
      <el-table-column label="ID" width="65" align="center" prop="id" />
      <el-table-column label="ADE KB Name" width="150" align="left" prop="name" show-overflow-tooltip />
      <el-table-column label="Collection Name" width="150" align="left" prop="collectionName" show-overflow-tooltip />
      <el-table-column label="Pos Rate" width="100" align="center" prop="posRate" />
      <el-table-column label="Pos Size" width="100" align="center" prop="posSize">
        <template slot-scope="scope">
          <span>{{ scope.row.posFinishSize || 0 }} / {{ scope.row.posSize || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Neg Size" width="100" align="center" prop="negSize">
        <template slot-scope="scope">
          <span>{{ scope.row.negFinishSize || 0 }} / {{ scope.row.negSize || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Total Size" width="100" align="center" prop="size">
        <template slot-scope="scope">
          <span>{{ computeTotal(scope.row) }} / {{ scope.row.size || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" width="140" align="center" prop="status">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <dict-tag :options="dict.type.lab_status" :value="scope.row.status" />
            <el-tooltip :content="scope.row.reason" v-if="scope.row.status === 'failed'" placement="top">
              <i class="el-icon-question" style="margin-left: 5px;"></i>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="Embed Model" width="200" align="center" prop="embedModel" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.embed_models" :value="scope.row.embedModel" />
        </template>
      </el-table-column>
      <el-table-column label="Description" align="left" prop="description" show-overflow-tooltip />
      <el-table-column label="Actions" width="240" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handelDetail(scope.row)">Detail</el-button>
          <el-button v-if="scope.row.status === 'ready'" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['ade:adebase:edit']">Edit</el-button>
          <el-button v-if="scope.row.status === 'ready' || scope.row.status === 'failed'" size="mini" type="text"
            icon="el-icon-edit" @click="handleExecute(scope.row)" v-hasPermi="['ade:lab:edit']">Execute</el-button>
          <el-button
            v-if="scope.row.status === 'failed' || scope.row.status === 'success' || scope.row.status === 'ready'"
            size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ade:adebase:remove']">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 添加或修改ADE Knowledge Base对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="120px" size="mini">

        <!--请输入ADE KB库名称-->
        <el-form-item label="ADE KB Name" prop="name">
          <el-input v-model="form.name" placeholder="Pls Input ADE KB Name" />
        </el-form-item>
        <!--
        <el-form-item label="Collection Name" prop="collectionName">
          <el-input v-model="form.collectionName" placeholder="请输入Milvuse Collection Name" />
        </el-form-item>
        -->
        <!--请输入ADE 库汇总正例比例-->
        <el-form-item label="Positive Rate" prop="posRate">
          <el-input-number v-model="form.posRate" placeholder="Positive Rate" />
        </el-form-item>

        <!--请输输入ADE 库 规模-->
        <el-form-item label="Size" prop="size">
          <el-input-number v-model="form.size" placeholder="Input Size" />
        </el-form-item>

        <!--请选择embedding 模型-->
        <el-form-item label="Embed Model" prop="embedModel">
          <el-select v-model="form.embedModel" placeholder="Select Embed Model">
            <el-option v-for="dict in dict.type.embed_models" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <!--请输入描述-->
        <el-form-item label="Description" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="Pls Input Description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">Confirm</el-button>
        <el-button @click="cancel">Cancel</el-button>
      </div>
      </el-dialog>

    <!-- ADE Knowledge Base Detail Dialog -->
      <el-dialog :visible.sync="showDialog" @close="handClose()" width="80%" :title="detailTitle">
        <adebase-detail-dialog v-if="selectedId" :id="selectedId" />
      </el-dialog>
  </div>
</template>

  <script>
  import { listAdebase, getAdebase, delAdebase, addAdebase, updateAdebase, executeAdebase } from "@/api/ade/adebase";

  import AdebaseDetailDialog from "@/views/ade/adebase/detail.vue";


  export default {
    name: "Adebase",
    dicts: ['lab_status', 'embed_models'],
    components: {
      AdebaseDetailDialog,
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // ADE Knowledge Base表格数据
        adebaseList: [],
        // 弹出层标题
        title: "",
        detailTitle: "", // 详情页面标题
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          collectionName: null,
          posRate: null,
          posSize: null,
          negSize: null,
          size: null,
          status: null,
          embedModel: null,
          description: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            { required: true, message: "Pls input ADE KB Name", trigger: "blur" },
            { min: 1, max: 50, message: "Length must be between 1 and 50 characters", trigger: "blur" }
          ],
          posRate: [
            { required: true, message: "Pls input Positive Rate", trigger: "blur" },
            { type: 'number', min: 0, max: 1, message: "Positive Rate must be between 0 and 1", trigger: "blur" }
          ],
          size: [
            { required: true, message: "Pls input Size", trigger: "blur" },
            { type: 'number', min: 1, message: "Size must be greater than 0", trigger: "blur" }
          ],
          embedModel: [
            { required: true, message: "Pls select Embed Model", trigger: "change" }
          ]
        },
        // 弹出层是否显示
        showDialog: false,
        // 选中的ID
        selectedId: null,
      };
    },
    created() {
      this.getList();
    },
    computed: {
    },
    methods: {
      //跳转到ADE Knowledge Base Result页面
      gotoRecord() {
        this.$router.push({ path: '/knowledge/adekbrecord' });
      },
      //打开标准数据集详情页面
      handelDetail(row) {
        this.detailTitle = row.name + " Detail";
        this.selectedId = row.id;
        this.showDialog = true;
      },
      handClose() {
        this.showDialog = false;
        this.selectedId = null;
      },
      // 计算总规模
      computeTotal(row) {
        return (row.posFinishSize || 0) + (row.negFinishSize || 0);
      },
      //提交执行ADE库的构建和索引
      handleExecute(row) {
        const id = row.id || this.ids
        this.$modal.confirm('Are you sure to execute ADE KB"' + id + '"?').then(() => {
          executeAdebase(id).then(response => {
            this.$modal.msgSuccess("Execution submitted:" + response.msg);
            this.getList();
          }).catch(() => {
            // this.$modal.msgError("Execution failed");
          });
        });
      },

      /** 查询ADE Knowledge Base列表 */
      getList() {
        this.loading = true;
        listAdebase(this.queryParams).then(response => {
          this.adebaseList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          collectionName: null,
          posRate: null,
          posSize: null,
          negSize: null,
          size: null,
          status: null,
          embedModel: null,
          description: null,
          createTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "New ADE KB";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getAdebase(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "Edit ADE KB";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.form.status = 'ready'; // 默认状态为 ready
        // 校验表单
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateAdebase(this.form).then(response => {
                this.$modal.msgSuccess("Updated successfully");
                this.open = false;
                this.getList();
              });
            } else {
              addAdebase(this.form).then(response => {
                this.$modal.msgSuccess("Added successfully");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('Are you sure to delete the ADE KB, Which id is "' + ids + '"？').then(function () {
          return delAdebase(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("Deleted successfully");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('ade/adebase/export', {
          ...this.queryParams
        }, `adebase_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>